/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2014 All Rights Reserved.
 */
package com.alipay.servlet.auth;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.alipay.constants.AlipayServiceEnvConstants;
import com.alipay.factory.AlipayAPIClientFactory;
import com.alipay.util.RequestUtil;

import net.sf.json.JSONObject;

/**
 * 用户信息共享（网页授权获取用户信息）
 * 
 * @author taixu.zqq
 * @version $Id: LoginAuthServlet.java, v 0.1 2014年7月25日 下午5:13:03 taixu.zqq Exp
 *          $
 */
public class LoginAuthServlet extends HttpServlet {

	/**  */
	private static final long serialVersionUID = -6807693807426739985L;
	
	static String  USER_INFO_SHARE_RESPONSE_OBJECT = "alipay_user_info_share_response";
	/**
	 * 业务处理
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1. 解析请求参数
		Map<String, String> params = RequestUtil.getRequestParams(request);
		// 2. 获得authCode
		String authCode = params.get("auth_code");
		System.out.println(authCode);
		try {
			AlipayClient alipayClient = AlipayAPIClientFactory.getAlipayClient();
			AlipaySystemOauthTokenRequest oauthTokenRequest = new AlipaySystemOauthTokenRequest();
			oauthTokenRequest.setCode(authCode);
			oauthTokenRequest.setGrantType(AlipayServiceEnvConstants.GRANT_TYPE);

			AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(oauthTokenRequest);
			System.out.println(oauthTokenResponse.getAccessToken());
			String accessToken = oauthTokenResponse.getAccessToken();

			// 通过accessToken获取用户信息
			AlipayUserInfoShareRequest shareRequest = new AlipayUserInfoShareRequest();
			AlipayUserInfoShareResponse userInfoShareResponse = alipayClient.execute(shareRequest, accessToken);
			if (userInfoShareResponse.isSuccess()) {
				System.out.println("调用成功");
				String responseBody = userInfoShareResponse.getBody();
				
				JSONObject resultJson = JSONObject.fromObject(responseBody);
				JSONObject o = (JSONObject) resultJson.get(USER_INFO_SHARE_RESPONSE_OBJECT);
				/*{"code":"10000","msg":"Success",
					"avatar":"https:\/\/tfs.alipayobjects.com\/images\/partner\/T1j3JdXmJqXXXXXXXX",
					"city":"武汉市",
					"gender":"m",
					"is_certified":"T",
					"is_student_certified":"F",
					"nick_name":"伟明",
					"province":"湖北省",
					"user_id":"2088702468804908",
					"user_status":"T",
					"user_type":"2"},*/
				if(o.containsKey("avatar")){
					request.setAttribute("userImg",  o.getString("avatar"));
				}else {
					request.setAttribute("userImg",  "您还没有上传头像，请上传您的靓照!");
				}
				
				if(o.containsKey("nick_name")){
					request.setAttribute("userName",  o.getString("nick_name"));
				}else {
					request.setAttribute("userName",  "您还没有实名吗?");
				}
				
				request.setAttribute("userCity", o.getString("city"));
				request.setAttribute("province", o.getString("province"));
				request.setAttribute("userId", o.getString("user_id"));
				System.out.println("11====>"+request.getAttribute("userImg"));
				System.out.println("授权成功后获取的用户信息====>" + responseBody);
			} else {
				System.out.println("调用失败");
			}

			System.out.println("=============================================================================");
			
			//同一个accessToken不能用两次
			/*AlipayOpenPublicContactFollowBatchqueryRequest contactFollowBatchqueryRequest = new AlipayOpenPublicContactFollowBatchqueryRequest();
			AlipayOpenPublicContactFollowBatchqueryResponse contactFollowBatchqueryResponse = alipayClient.execute(contactFollowBatchqueryRequest,
					accessToken);
			if (contactFollowBatchqueryResponse.isSuccess()) {
				System.out.println("调用成功");
				String responseBody = contactFollowBatchqueryResponse.getBody();
				System.out.println("查询服务窗联系人关注列表====>" + responseBody);
			} else {
				System.out.println("调用失败");
			}*/
		} catch (AlipayApiException alipayApiException) {
			// 自行处理异常
			alipayApiException.printStackTrace();
		}
		
		// 可以将页面跳转到任何路径，不局限于web应用中，跳转的过程中url地址变化，无法使用request.setAttribute来传递。
		//response.sendRedirect("/a.jsp");
		
		 // url地址不变，只能跳转到本web应用中的页面上。可以用request.setAttibute方法
		
		 request.getRequestDispatcher("/index2.jsp").forward(request,response);
	}
	public static void main(String[] args) {
		JSONObject o = new JSONObject();
		o.put("ss", "a");
		System.out.println(o.containsKey("a"));
		
		
		
	}
}
